package cn.kgc.vue.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.kgc.vue.commons.QueryCondition;
import cn.kgc.vue.commons.ResponseResult;
import cn.kgc.vue.entity.LogInfo;
import cn.kgc.vue.service.LogInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @author 课工场
 * @date 2023/12/15
 * @description
 */
@Api(tags = "日志模快")
@RestController
@RequestMapping("logs")
public class LogInfoController {


    @Resource
    private LogInfoService logInfoService;

    @ApiOperation("日志列表")
    @PostMapping("list")
    public ResponseResult getLogsList(@RequestBody QueryCondition<LogInfo> queryCondition){

        return   logInfoService.getLogsList(queryCondition);
    }

    @ApiOperation("批量删除日志")
    @DeleteMapping
    public ResponseResult deleteLogsList(@RequestBody Integer[] ids){
        List<Integer> list = Arrays.asList(ids);
        logInfoService.removeBatchByIds(list);
        return ResponseResult.success().message("删除成功")  ;
    }


    @ApiOperation("导出日志")
    @GetMapping("excel")
    public void exportLogsList(HttpServletResponse response,String username,String ip,String model) throws IOException {

        LambdaQueryWrapper<LogInfo> lambda = new QueryWrapper<LogInfo>().lambda();
        lambda.eq(StringUtils.isNotEmpty(username),LogInfo::getUsername,username)
                .eq(StringUtils.isNotEmpty(ip),LogInfo::getIp,ip)
                .eq(StringUtils.isNotEmpty(model),LogInfo::getModel,model)
                .orderByDesc(LogInfo::getCreateTime);

        List<LogInfo> list = logInfoService.list(lambda);

        ExportParams exportParams = new ExportParams("日志信息", "日志表");

        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, LogInfo.class, list);
        ServletOutputStream outputStream = response.getOutputStream();

        workbook.write(outputStream);
        workbook.close();
        outputStream.close();

    }

}
